"""
@file:   user.py
@author: Shuai
@date:   2020/04/30
"""
from flask import Blueprint
from flask import request
from models.user import User, Sms_phone
from models.base import db
import random
import requests
from requests.auth import HTTPBasicAuth
from libs.nestable_blueprint import NestableBlueprint
from flask_sqlalchemy import SQLAlchemy
from libs.response import generate_response
# user_bp = NestableBlueprint('user', __name__, url_prefix='/user')

user_bp = Blueprint('user', __name__, url_prefix='/user/')


@user_bp.route('/login/', methods=['POST'])
def login():
    return '这是登录接口'


@user_bp.route('/register/', methods=['POST'])
def register():
    data = request.get_json()['data']
    print(data, type(data))
    return 'gan'


@user_bp.route('/sendphone/', methods=['POST'])
def sendphone():
    # 前端传的数据{'data': {'phone': '13111111111'}} <class 'dict'>
    # 获取到注册的电话号码，先验证是否已注册，如果注册返回已注册，否则发送验证码
    phonenum = request.json['data']['phone']
    if User.query.filter(User.user_phone == phonenum).first():
        return "该手机号已经注册"
    else:
        # 生成并发送6验证码
        sms = random.randint(100000, 999900)
        # print(sms)
        # # 向三方短信验证api请求  params是上传的参数：sms，电话号码，headers是平台登录验证
        # r = requests.get('https://feginesms.market.alicloudapi.com/codeNotice',
        #                  params={'param': f'{sms}', 'phone': f'{phonenum}', 'sign': '175622', 'skin': '8'},
        #                  headers={"Authorization": "APPCODE 448089275aeb4455ae54434ce7a00b7a"})
        # print(r)
        sms_ph = Sms_phone.query.filter(Sms_phone.phone_num == phonenum)
        if Sms_phone.query.filter(Sms_phone.phone_num == phonenum).first():
            sms_ph.update({'sms_num': str(sms)})
            # db.session.add(sms_ph)
            db.session.commit()
        else:
            sms_phone = Sms_phone(phone_num=phonenum, sms_num=sms)
            db.session.add(sms_phone)
            db.session.commit()

        return "ok"


# @user_bp.route('/getcode/', methods=['GET'])
# def getcode():
#     sms = '131'
#     return sms


@user_bp.route('/change/', methods=['PUT'])
def change():
    return '这是修改接口'
